package GinResp

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

type RespImpl struct {
	Status int
	Message string
	Data interface{}
}

func (r RespImpl) DataResp(ctx *gin.Context, data interface{}) {
	respImpl := RespImpl{Status: 0, Message: "success", Data: data}

	switch data.(type) {
	case string:
		ctx.JSON(http.StatusOK, gin.H{
			"status": respImpl.Status,
			"message": respImpl.Data,
		})

	default:
		ctx.JSON(http.StatusOK, gin.H{
			"status": respImpl.Status,
			"message": respImpl.Message,
			"result": respImpl.Data,
		})
	}
}

func (r RespImpl) ErrResp(ctx *gin.Context, err interface{}) {
	fmt.Printf("%v\n", err)
	errorStr := fmt.Sprintf("%s", err)
	respImpl := RespImpl{Status: 1, Message: "error"}

	ctx.JSON(http.StatusOK, gin.H{
		"status": respImpl.Status,
		"message": respImpl.Message,
		"data": errorStr,
	})
}

func (r RespImpl) ErrResp2(ctx *gin.Context) {
	if err := recover(); err != nil {
		errorStr := fmt.Sprintf("%s", err)
		respImpl := RespImpl{Status: 1, Message: "error"}

		ctx.JSON(http.StatusOK, gin.H{
			"status": respImpl.Status,
			"message": respImpl.Message,
			"data": errorStr,
		})
	}
}
